<?php
//-------------------------------------------------------------------------
// OVIDENTIA http://www.ovidentia.org
// Ovidentia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//-------------------------------------------------------------------------
/**
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
 * @copyright Copyright (c) 2006 by CANTICO ({@link http://www.cantico.fr})
 */
include_once 'base.php';
require_once $GLOBALS['babInstallPath'] . 'utilit/urlincl.php';
require_once $GLOBALS['babInstallPath'] . '/addons/widgets/widgets/lineedit.class.php';




/**
 * Widget_SuggestEdit.
 */
class Widget_SuggestEdit extends Widget_InputWidget
{
	/**
	 * Proposition of a limit to use in scripts for calls to addSuggestion
	 * @see Widget_SuggestEdit::addSuggestion()
	 * @var	int
	 */
	const MAX = 100;

	/**
	 * Name of the id field
	 * @var string
	 */
	protected $id_name = null;


	/**
	 * Value of the id field
	 * @var string
	 */
	protected $id_value = '';


	private $suggestlist = array();



	/**
	 * @param string $id			The item unique id.
	 * @return Widget_SuggestEdit
	 */
	public function __construct($id = null)
	{
		parent::__construct($id);

		$this->setMetadata('suggesturl', $_GET + $_POST);
		$this->setMetadata('suggestparam', $this->getId().'_search');
		$this->setMetadata('keyup', array());
		$this->setMetadata('id_target', $this->getId().'_ID');
	}


	/**
	 *
	 * @param Widget_Action $action The widget_Action that should
	 * 			                    return the json encoded result as
	 *                              the sendSuggestions() method.
	 *
	 *  @return Widget_SuggestEdit
	 */
	public function setSuggestAction(Widget_Action $action)
	{
		$this->setMetadata('suggesturl', $action->getParameters());
		return $this;
	}

	/**
	 * Convert an array as query string
	 *
	 * @param	string	$name
	 * @param	array	$arr
	 *
	 * @return	string
	 */
	private static function urlAsArray($name, $arr) {

		$params = array();

		foreach($arr as $key => $value) {

			if (!is_null($value)) {
				if (is_array($value)) {
					$params[] = self::urlAsArray($name.'['.$key.']', $value);
				} else {
					$params[] = urlencode($name.'['.$key.']').'='.urlencode($value);
				}
			}
		}

		return implode('&', $params);
	}





	/**
	 * get search keyword
	 * return a string search keyword if the widget try to get suggestions
	 * or false if the widget does not search for suggestions
	 *
	 * @return false|string
	 */
	public function getSearchKeyword() {

		$keyword = bab_rp($this->getMetadata('suggestparam'), false);

		if (false === $keyword)
		{
			return false;
		}

		$keyword = bab_getStringAccordingToDataBase($keyword, 'UTF-8');

		return $keyword;
	}



	/**
	 * Add a suggestion
	 * id, info and extra can be pushed in other fields on suggest selection, this can be done using the coresponding metadata
	 * 	<ul>
	 * 		<li>id_target</li>
	 * 		<li>info_target</li>
	 * 		<li>extra_target</li>
	 *  </ul>
	 * each metadata can contain a widget id
	 *
	 *
	 * @param	string	$id			id of the suggestion string, not displayed, @see Widget_SuggestEdit::getSuggestId()
	 * @param	string	$value		value is the main suggestion string, it will be set in input value on click
	 * @param	string	$info		info is displayed under the value in smaller font
	 * @param	string	$extra		extra is not used by default
	 *
	 * @return 	Widget_SuggestEdit
	 */
	public function addSuggestion($id, $value, $info = '', $extra = '') {
		$this->suggestlist[] = array(
			'id' 	=> $id,
			'value'	=> $value,
			'info'	=> $info,
			'extra'	=> $extra
		);

		return $this;
	}


	/**
	 * Send suggestions if necessary
	 * @return 	Widget_SuggestEdit
	 */
	public function sendSuggestions() {
		if (false === $this->getSearchKeyword()) {
			return $this;
		}

		echo '[';

		foreach($this->suggestlist as $arr) {
			echo "{\n";
			echo "'id'		:'".bab_toHtml($arr['id']		, BAB_HTML_JS)."',\n";
			echo "'value'	:'".bab_toHtml($arr['value']	, BAB_HTML_JS)."',\n";
			echo "'info'	:'".bab_toHtml($arr['info']		, BAB_HTML_JS)."',\n";
			echo "'extra'	:'".bab_toHtml($arr['extra']	, BAB_HTML_JS)."'\n";
			echo "},\n";
		}

		echo ']';

		die();
	}


	/**
	 * Defines the minimum number of chars to type before autocompletion is triggered.
	 *
	 * @param int $minChars
	 * @return Widget_SuggestEdit
	 */
	public function setMinChars($minChars)
	{
		$this->setMetadata('minChars', $minChars);
		return $this;
	}


	/**
	 * Set a javascript function name to call when the value is modified in the input
	 * this can be by user input or by selection of a suggestion
	 *
	 * @param 	string 	$js_function
	 * @param	string	$domain
	 *
	 * @return Widget_SuggestEdit
	 */
	public function onKeyUp($js_function, $domain = 'window.babAddonWidgets')
	{
		$arr = $this->getMetadata('keyup');
		$arr[] = $domain.'.'.$js_function;

		$this->setMetadata('keyup', $arr);
		return $this;
	}




	/**
	 * Get request value from full name
	 * @param Array $fullname
	 * @return string | null
	 */
	private function getRequestValueFromName(Array $fullname)
	{
		$r = $_REQUEST;
		foreach($fullname as $name) {
			if (isset($r[$name])) {
				$r = $r[$name];
			} else {
				return null;
			}
		}

		return $r;
	}












	/**
	 * Set the name of ID hidden field
	 * if the the id name is not set with this method, the id property of suggestion will not be accessible
	 * if the id name is set a hidden field with this name will exists
	 *
	 * @param	string	$name
	 * @return Widget_SuggestEdit
	 */
	public function setIdName($name)
	{
		$this->id_name = $name;
		return $this;
	}



	/**
	 * Set the value of ID hidden field
	 *
	 * @see Widget_SuggestEdit::setIdName()
	 *
	 * @param	string	$value
	 * @return Widget_SuggestEdit
	 */
	public function setIdValue($value)
	{
		$this->id_value = $value;
		return $this;
	}


	/**
	 * Use multivalues mode in suggest field
	 * @param string $separator
	 * @return Widget_SuggestEdit
	 */
	public function setMultiple($separator)
	{
		assert('is_string($separator); /* The "separator" parameter must be a string. */');
		assert('0 < mb_strlen($separator); /* The "separator" parameter must not be empty. */');

		// TODO : pour le moment seul la virgule est autorisee, a corriger
		$separator = ',';

		$this->setMetadata('multiple_separator', $separator);
		return $this;
	}



	/**
	 *
	 */
	public function getClasses()
	{
		$classes = parent::getClasses();
		$classes[] = 'widget-suggestedit';
		return $classes;
	}


	/**
	 *
	 */
	public function display(Widget_Canvas $canvas) {

		$output = '';

		if (null !== $this->id_name) {

			$fullname = $this->getFullName();
			$fullname[count($fullname) -1] = $this->id_name;

			$output .= $canvas->hidden($this->getId().'_ID', null, $fullname, $this->id_value);
		}

		return $output;
	}

}
